import { existsSync, readdirSync, statSync } from "fs";
import path from "path";

/******************************************************************************************************
 * 
 * 
 * 
 *****************************************************************************************************/

let skipList: string[] = [];

export function AddToSkipList(list: string[]) {
    skipList = skipList.concat(list);
}

export async function LoadFiles(dirname: string, fileUrlList: string[]) {
    fileUrlList.forEach(fileUrl => {
        const fullUrl = path.join(dirname, fileUrl);
        let stat = statSync(fullUrl);
        if (stat.isFile()) {
            // console.log(`[Load Files] : ${fullUrl}`);
            let moduleExtName = path.extname(fullUrl);
            let moduleName = fullUrl.replace(moduleExtName, "");
            // if (require.cache && require.cache[moduleName]) {
            //     console.info(`${moduleName} has required!`);
            // } else {
            //     require(moduleName);
            // }
            require(moduleName);
        }
    });
}

export async function LoadModules(url: string) {
    let isExist = existsSync(url);
    if (!isExist) {
        console.warn(`${url} not exist`);
        return;
    }
    let list = readdirSync(url);
    for (let key in list) {
        let filename = list[key];
        if (skipList.indexOf(filename) != -1) {
            continue;
        }
        let extname = path.extname(filename);
        if (extname == ".meta") {
            continue;
        }
        let fullUrl = path.resolve(url, filename);
        let stat = statSync(fullUrl);
        if (stat.isFile()) {
            // console.log(`[Load Module] : ${fullUrl}`);
            let moduleExtName = path.extname(fullUrl);
            let moduleName = fullUrl.replace(moduleExtName, "");
            // if (require.cache && require.cache[moduleName]) {
            //     console.info(`${moduleName} has required!`);
            // } else {
            //     require(moduleName);
            // }
            require(moduleName);
        } else if (stat.isDirectory()) {
            LoadModules(fullUrl);
        } else {
            console.error(stat);
        }
    }
}